import 'dart:convert';
import 'dart:ui';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_yres/model/jiayouList_model.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_yres/tool/constant.dart';
import 'package:flutter_yres/pages/jiayouzhan/jyz_detail_page.dart';
import 'package:jlocation/jlocation.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_yres/tool/AppSaveInfoUtil.dart';
import '../login/login_page.dart';
import 'package:flutter_yres/tool/Toast.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:amap_location_fluttify/amap_location_fluttify.dart';
import '../../tool/MYLoading.dart';
import '../../pages/jiayouzhan/goMap.dart';

class JYZListPage extends StatefulWidget {
  @override
  _JYZListPageState createState() => _JYZListPageState();
}

class _JYZListPageState extends State<JYZListPage> {
  double _listHeight = ScreenUtil.getInstance().setHeight(210); //单个列表高度
  EasyRefreshController _controller = new EasyRefreshController();
  int jyz_page = 1;
  List<JYZModelData> jyzListData = []; //加油站数组
  String rectangle;
  String ip;
  double lat, lng;
  String token;
  //加油站参数
  List<DropdownMenuItem> jyz_distanceItemList() {
    List<DropdownMenuItem> items = new List();
    DropdownMenuItem item1 = new DropdownMenuItem(
        value: '1000',
        child: new Text(
          '1千米',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item2 = new DropdownMenuItem(
        value: '3000',
        child: new Text(
          '3千米',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item3 = new DropdownMenuItem(
        value: '5000',
        child: new Text(
          '5千米',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item4 = new DropdownMenuItem(
        value: '10000',
        child: new Text(
          '10千米',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    items.add(item1);
    items.add(item2);
    items.add(item3);
    items.add(item4);
    return items;
  }

  var jyz_selectDistanceItemValue;
  var jyz_selectoilNoItemValue;
  var jyz_selectCondItemValue;
  var jyz_selectGasTypeItemValue;
  List<DropdownMenuItem> jyz_oilNotemList() {
    List<DropdownMenuItem> items = new List();
    DropdownMenuItem item1 = new DropdownMenuItem(
        value: '92',
        child: new Text(
          '#92',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item2 = new DropdownMenuItem(
        value: '95',
        child: new Text(
          '#95',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item3 = new DropdownMenuItem(
        value: '98',
        child: new Text(
          '#98',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item4 = new DropdownMenuItem(
        value: '0',
        child: new Text(
          '#0',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    items.add(item1);
    items.add(item2);
    items.add(item3);
    items.add(item4);
    return items;
  }

  List<DropdownMenuItem> jyz_condtemList() {
    List<DropdownMenuItem> items = new List();
    DropdownMenuItem item1 = new DropdownMenuItem(
        value: '1',
        child: new Text(
          '油价升序',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item2 = new DropdownMenuItem(
        value: '2',
        child: new Text(
          '距离升序',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    items.add(item1);
    items.add(item2);
    return items;
  }

  List<DropdownMenuItem> jyz_gasTypetemList() {
    List<DropdownMenuItem> items = new List();
    DropdownMenuItem item1 = new DropdownMenuItem(
        value: '1',
        child: new Text(
          '中石油',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item2 = new DropdownMenuItem(
        value: '2',
        child: new Text(
          '中石化',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item3 = new DropdownMenuItem(
        value: '3',
        child: new Text(
          '壳牌',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    DropdownMenuItem item4 = new DropdownMenuItem(
        value: '4',
        child: new Text(
          '其他',
          style: TextStyle(
            fontSize: 14,
          ),
          textAlign: TextAlign.center,
        ));
    items.add(item1);
    items.add(item2);
    items.add(item3);
    items.add(item4);
    return items;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('加油'),
      ),
      body: jyzListData.length == 0
          ? new NetLoadingDialog(
              dismissCallback: _disMissCallBack,
              outsideDismiss: false,
            )
          : new Stack(
              children: <Widget>[
                Container(
                    margin: EdgeInsets.fromLTRB(
                        0, ScreenUtil.getInstance().setHeight(40), 0, 0),
                    child: EasyRefresh(
                        controller: _controller,
                        header: MaterialHeader(),
                        footer: MaterialFooter(),
                        enableControlFinishLoad: true,
                        enableControlFinishRefresh: true,
                        child: CustomScrollView(slivers: <Widget>[
                          SliverToBoxAdapter(child: Container()),
                          SliverFixedExtentList(
                              delegate: _buildTypeList(),
                              itemExtent: _listHeight),
                          SliverToBoxAdapter(
                            child: Container(),
                          ),
                        ]),
                        onRefresh: () async {
                          jyz_page = 1;
                          loc();
                        },
                        onLoad: () async {
                          jyz_page++;
                          _loadList();

                          // getJYStationList(
                          //     jyz_selectGasTypeItemValue,
                          //     jyz_selectDistanceItemValue,
                          //     jyz_selectoilNoItemValue,
                          //     jyz_selectCondItemValue);
                        })),
                _buildPopHeader()
              ],
            ),
    );
  }

  SliverChildDelegate _buildTypeList() {
    return SliverChildBuilderDelegate(_buildListItem,
        childCount: jyzListData.length);
  }

  _buildPopHeader() {
    //条件筛选头部
    var jyz_header = Container(
      height: ScreenUtil.getInstance().setHeight(40),
      width: ScreenUtil.getInstance().setWidth(750),
      child: Row(
        children: <Widget>[
          // Expanded(
          //     flex: 1,
          //     child: Container(
          //       alignment: Alignment.center,
          //       child: new DropdownButtonHideUnderline(
          //         child: new DropdownButton(
          //           iconSize: 20.0,
          //           hint: new Text(
          //             '距离',
          //             style: TextStyle(
          //               fontSize: 14,
          //             ),
          //             textAlign: TextAlign.center,
          //           ),
          //           value: jyz_selectDistanceItemValue,
          //           items: jyz_distanceItemList(),
          //           onChanged: (T) {
          //             setState(() {
          //               jyz_selectDistanceItemValue = T;
          //               // _refreshList();
          //               empower();
          //             });
          //           },
          //         ),
          //       ),
          //     )),
          Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.center,
                child: new DropdownButtonHideUnderline(
                  child: new DropdownButton(
                    iconSize: 20.0,
                    hint: new Text(
                      '油号编码',
                      style: TextStyle(
                        fontSize: 14,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    value: jyz_selectoilNoItemValue,
                    items: jyz_oilNotemList(),
                    onChanged: (T) {
                      setState(() {
                        jyz_selectoilNoItemValue = T;
                        // _refreshList();
                        empower();
                      });
                    },
                  ),
                ),
              )),
          Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.center,
                child: new DropdownButtonHideUnderline(
                  child: new DropdownButton(
                    iconSize: 20.0,
                    hint: new Text(
                      '排序',
                      style: TextStyle(
                        fontSize: 14,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    value: jyz_selectCondItemValue,
                    items: jyz_condtemList(),
                    onChanged: (T) {
                      setState(() {
                        jyz_selectCondItemValue = T;
                        // _refreshList();
                        empower();
                      });
                    },
                  ),
                ),
              )),
          Expanded(
              flex: 1,
              child: Container(
                alignment: Alignment.center,
                child: new DropdownButtonHideUnderline(
                  child: new DropdownButton(
                    iconSize: 20.0,
                    hint: new Text(
                      '加油站类型',
                      style: TextStyle(
                        fontSize: 14,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    value: jyz_selectGasTypeItemValue,
                    items: jyz_gasTypetemList(),
                    onChanged: (T) {
                      setState(() {
                        jyz_selectGasTypeItemValue = T;
                        // _refreshList();
                        empower();
                      });
                    },
                  ),
                ),
              ))
        ],
      ),
    );
    return jyz_header;
  }

/***************************加油站数据列表**************************/
  Widget _buildListItem(BuildContext context, int index) {
    return new GestureDetector(
        onTap: () {
          //处理点击事件
          JYZModelData model = jyzListData[index];
          // var gasIds=model.gasid;
          Navigator.push(
              context,
              MaterialPageRoute(
                  //导航打开新视图
                  builder: (context) =>
                      JYZDetailPage(model: model) //打开第二个页面，并传值，传递值的名称是model
                  ));
        },
        child: Container(
            margin: EdgeInsets.fromLTRB(
                0, ScreenUtil.getInstance().setHeight(15), 0, 0),
            child: Column(
              children: <Widget>[
                Row(children: <Widget>[
                  _leftImage(index),
                  Expanded(
                    child: _rightColumn(index),
                  )
                ], crossAxisAlignment: CrossAxisAlignment.start),
                Divider(
                  height: 1,
                )
              ],
            )));
  }

  Widget _pd(Widget w, {double l, double t, double r, double b}) {
    //边距
    return Padding(
        padding: EdgeInsets.fromLTRB(
            ScreenUtil.getInstance().setWidth(l) ?? 0,
            ScreenUtil.getInstance().setHeight(t) ?? 0,
            ScreenUtil.getInstance().setWidth(r) ?? 0,
            ScreenUtil.getInstance().setHeight(b) ?? 0),
        child: w);
  }

  Widget _leftImage(int index) {
    //左图
    var image = CachedNetworkImage(
      width: ScreenUtil.getInstance().setHeight(150),
      height: ScreenUtil.getInstance().setHeight(150),
      fit: BoxFit.fill,
      imageUrl: jyzListData[index].gaslogosmall,
      placeholder: (context, url) => Image.asset('images/pic_default.png',
          width: ScreenUtil.getInstance().setHeight(150),
          height: ScreenUtil.getInstance().setHeight(150),
          fit: BoxFit.fill),
      errorWidget: (context, url, error) => Image.asset(
          'images/pic_default.png',
          width: ScreenUtil.getInstance().setHeight(150),
          height: ScreenUtil.getInstance().setHeight(150),
          fit: BoxFit.fill),
    );
    return _pd(image, l: 20, t: 0, r: 5, b: 40);
  }

  Widget _rightColumn(int index) {
    //右内容
    var title = Text(
      jyzListData[index].gasname,
      style: TextStyle(color: Colors.black, fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE+3)),
      maxLines: 2,
      overflow: TextOverflow.ellipsis,
    );
    var price = RichText(
      text: TextSpan(style: TextStyle(color: Colors.red), children: [
        TextSpan(text: '¥', style: TextStyle(fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE))),
        TextSpan(
            text: jyzListData[index].priceyfq,
            style: TextStyle(fontSize: ScreenUtil.getInstance()
                                  .setSp(NORMAL_FONT_SIZE))),
        TextSpan(
            text: '/升/' + jyzListData[index].oilname,
            style: TextStyle(fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE))),
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    var distance = RichText(
      text: TextSpan(style: TextStyle(fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE)), children: [
        TextSpan(
            text: jyzListData[index].distance == null ||
                    jyzListData[index].distance == ''
                ? ''
                : formatNum(double.parse(jyzListData[index].distance) / 1000, 2)
                        .toString() +
                    'km',
            style: TextStyle(color: Colors.grey)),
        // TextSpan(text: '导航', style: TextStyle(color: Colors.orange)),
      ]),
    );
    var address = Text(
      jyzListData[index].provincename +
          jyzListData[index].cityname +
          jyzListData[index].countyname +
          jyzListData[index].gasaddress,
      style: TextStyle(color: Colors.grey, fontSize:ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE)),
      maxLines: 2,
      overflow: TextOverflow.ellipsis,
    );
    return new Column(
      children: <Widget>[
        _pd(title, l: 10, t: 0, r: 10, b: 8),
        Row(
          children: <Widget>[
            _pd(price, l: 10, t: 0, r: 10, b: 8),
             Expanded(
              child: distance,
            ),
            GestureDetector(
                onTap: () {
                  showDialog(
                      context: context,
                      builder: (context) {
                        return new SimpleDialog(
                          title: new Text("选择地图"),
                          children: <Widget>[
                            new SimpleDialogOption(
                              child: new Text("高德地图"),
                              onPressed: () {
                                MapUtil.gotoAMap(
                                    jyzListData[index].gasaddresslongitude,
                                    jyzListData[index].gasaddresslatitude,
                                    jyzListData[index].gasaddress
                                    );
                              },
                            ),
                            new SimpleDialogOption(
                              child: new Text("百度地图"),
                              onPressed: () {
                                MapUtil.gotoBaiduMap(
                                    jyzListData[index].gasaddresslongitude,
                                    jyzListData[index].gasaddresslatitude,
                                    jyzListData[index].gasaddress
                                    );
                              },
                            ),
                            // new SimpleDialogOption(
                            //   child: new Text("腾讯地图"),
                            //   onPressed: () {
                            //     MapUtil.gotoTencentMap(
                            //         jyzListData[index].gasaddresslongitude,
                            //         jyzListData[index].gasaddresslatitude,
                            //         jyzListData[index].gasaddress
                            //         );
                            //   },
                            // ),
                            new SimpleDialogOption(
                              child: new Text("取消"),
                              onPressed: () {
                                Navigator.of(context).pop();
                              },
                            ),
                          ],
                        );
                      });
                },
                child: Container(
                    margin: EdgeInsets.only(
                        right: ScreenUtil.getInstance().setWidth(10)),
                    child: Text(
                      '导航',
                      style: TextStyle(color: mainColor,fontSize: ScreenUtil.getInstance().setSp(30)),
                    )))
          ],
        ),
        _pd(address, l: 10, t: 0, r: 10, b: 8)
      ],
      crossAxisAlignment: CrossAxisAlignment.start,
    );
  }

  @override
  void initState() {
    _getLoginMsg();
    jyz_page = 1;
    super.initState();
  }

  @override
  void dispose() {
    // AMapLocationClient.shutdown();
    super.dispose();
  }

  //这个func 就是关闭Dialog的方法，在适当的时候关闭即可
  _disMissCallBack(Function func) {
    func();
  }

  String formatNum(double num, int postion) {
    if ((num.toString().length - num.toString().lastIndexOf(".") - 1) <
        postion) {
      //小数点后有几位小数
      return (num.toStringAsFixed(postion)
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString());
    } else {
      return (num.toString()
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString());
    }
  }

  empower() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    Map map = new Map();
    map['phone'] = preferences.get("name");
    FormData data = FormData.fromMap(new Map<String, dynamic>.from(map));
    Response<String> response =
        await HttpUtil().post(Api.kGetEmpowerURL, data: data);
    Map userMap = json.decode(response.data);
    print('加油站授权');
    print(userMap);
    if (userMap['code'] == 1) {
      if (mounted) {
        // if (jyz_page == 1) {
        _refreshList();
        // } else {
        //   _loadList();
        // }
      }
    }
  }

  void _refreshList() {
    jyz_page = 1;
    getJYStationList(jyz_selectGasTypeItemValue, jyz_selectDistanceItemValue,
        jyz_selectoilNoItemValue, jyz_selectCondItemValue);
  }

  void _loadList() {
    // jyz_page++;
    getJYStationList(jyz_selectGasTypeItemValue, jyz_selectDistanceItemValue,
        jyz_selectoilNoItemValue, jyz_selectCondItemValue);
  }

/*获取列表数据*/
  getJYStationList(gasType, distinct, oilNo, cond) async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    Map map = new Map();
    // map['token']=token;
    map['phone'] = preferences.get("name");
    map['page'] = jyz_page.toString();
    map['per'] = '8';
    map['cond'] = '2';
    if (distinct != null) {
      map['distinct'] = distinct;
    }
    if (cond != null) {
      map['cond'] = cond;
    }
    if (gasType != null) {
      map['gasType'] = gasType;
    }
    if (lat != null) {
      map['lng_lat'] = lng.toString() + "," + lat.toString();
    }
    if (rectangle != null) {
      map['lng_lat'] = rectangle;
    }
    print(map);
    FormData data = FormData.fromMap(new Map<String, dynamic>.from(map));
    print(data);
    Response<String> response =
        await HttpUtil().post(Api.kGetGasoilURL, data: data);
    Map userMap = json.decode(response.data);
    JYZModelEntity jyzEntity = new JYZModelEntity.fromJson(userMap);
    print(userMap);
    Toast.toast(context, msg: jyzEntity.msg);
    if (jyzEntity.code == 1) {
      if (mounted) {
        setState(() {
          if (jyz_page == 1) {
            _controller.finishRefresh();
            jyzListData.clear();
            jyzListData.addAll(jyzEntity.data);
          } else {
            _controller.finishLoad();
            jyzListData.addAll(jyzEntity.data);
          }
        });
      }
    }
  }

  //获取用户登录信息
  void _getLoginMsg() async {
    getString(TOKEN).then((value) {
      setState(() {
        token = value;
        if (value == null || value == '') {
          // isLogin = true;
          Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
            return new LoginPage();
          }));
        } else {
          loc();
        }
      });
    });
  }

  loc() async {
    if (Platform.isIOS) {
      abloc();
    } else if (Platform.isAndroid) {
      PermissionStatus permission = await PermissionHandler()
          .checkPermissionStatus(PermissionGroup.location);
      // print("dsfasdfsd"+ permission.toString());
      if (permission == PermissionStatus.granted) {
        final location = await AmapLocation.fetchLocation();
        print("test  " + location.toString());
        // lng = location.latLng as double;
        // location.latLng.then((value) {
        //   print(value);
        //   lat = value.latitude;
        //   lng = value.longitude;
        //   // _refreshList();
        //   empower();
        // });
         setState(() {
 lat = location.latLng.latitude;
          lng = location.latLng.longitude;
          empower();
        });
      } else {
        await PermissionHandler()
            .requestPermissions([PermissionGroup.location]);
        loc();
      }
    }
  }

  abloc() async {
    String url =
        "https://webapi.amap.com/maps/ipLocation?key=7a608be3db2f08377a8dbc098421ab64&callback=jsonp_199126_&csid=6E386226-2410-470F-B0C5-09D7DE9CF03F";
    Response<String> response = await HttpUtil().get(url);
    // Map userMap = json.decode(response.data);
    //  Map userMap = json.decode(response.data);
    print('==========定位==============');
    List s = response.data.split('jsonp_199126_(');
    List s2 = s[1].split(')');
    print(response.data.split('jsonp_199126_('));
    print(s2[0]);
    Map userMap = json.decode(s2[0]);
    setState(() {
      if (userMap['status'].toString() == '1') {
        lat = double.parse(userMap['lat']);
        lng = double.parse(userMap['lng']);
        print(lng.toString());
        print(lat.toString());
        // _refreshList();
        empower();
      } else {
        bloc();
      }
    });
  }

  bloc() async {
    String url = "https://ip.seeip.org/geoip";
    Response<String> response = await HttpUtil().get(url);
    Map userMap = json.decode(response.data);
    // print(userMap);
    setState(() {
      ip = userMap['ip'];
      cloc(ip);
      //  lat = userMap['latitude'];
      // lng = userMap['longitude'];
      // _refreshList();
    });
  }

  cloc(String theip) async {
    String url =
        'https://restapi.amap.com/v3/ip?output=json&key=fc9ab3e41e05ebc633244a07a83e1b1f&ip=' +
            theip;
    Response<String> response = await HttpUtil().get(url);
    Map userMap = json.decode(response.data);
    print('==========定位==============');
    print(userMap);
    setState(() {
      if (userMap['status'].toString() == '1') {
        List s = userMap['rectangle'].toString().split(';');
        rectangle = s[0];
        // _refreshList();
        empower();
        //  lat = userMap['latitude'];
        // lng = userMap['longitude'];
      }
    });
  }

  getLocation() async {
    PermissionStatus permission = await PermissionHandler()
        .checkPermissionStatus(PermissionGroup.notification);
    if (permission == PermissionStatus.granted) {
      var loc = new Jlocation();
      loc.onLocationChanged().listen((loc) {
        print('定位');
        setState(() {
          lat = loc.latitude;
          lng = loc.longitude;
          print(lat);
          jyz_page = 1;
          // _refreshList();
          empower();
        });
      });
    } else {
      Map<PermissionGroup, PermissionStatus> permissions =
          await PermissionHandler()
              .requestPermissions([PermissionGroup.location]);
      getLocation();
    }
  }
}
